package com.yyt.yytcodesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Config;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.util.List;

public class DockerDemo {
    public static void main(String[] args) throws InterruptedException {
        DockerClient dockerClient= DockerClientBuilder.getInstance().build();
//        PingCmd pingCmd = dockerClient.pingCmd();
//        pingCmd.exec();
        //拉取镜像
        String image="nginx:latest";
//        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
//        PullImageResultCallback pullImageResultCallback=new PullImageResultCallback(){
//            @Override
//            public void onNext(PullResponseItem item) {
//                System.out.println("下载镜像"+item.getStatus());
//                super.onNext(item);
//            }
//        };
//        pullImageCmd
//                .exec(pullImageResultCallback)
//                .awaitCompletion();
//        System.out.println("下载完成");

        //创建容器
//        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
//        CreateContainerResponse createContainerResponse = containerCmd.exec();
//        System.out.println(createContainerResponse);

        //获取容器列表
//        ListContainersCmd ListContainersCmd = dockerClient.listContainersCmd();
//        List<Container> configList = ListContainersCmd.withShowAll(true).exec();
//        for (Container container : configList) {
//            System.out.println(container.getId()+container.getNames());
//        }

        //启动容器\
        String startId="898ea4a2842c2d6e9134493d2bf173104b66c0a5ce0d38f00f9c2659b3e66cf5";
//        StartContainerCmd startContainerCmd = dockerClient.startContainerCmd(startId);
//        startContainerCmd.exec();

        //查看日志
        LogContainerCmd logContainerCmd = dockerClient.logContainerCmd(startId);
        //异步
        LogContainerResultCallback logContainerResultCallback=new LogContainerResultCallback(){
            @Override
            public void onNext(Frame item) {
                System.out.println("日志"+new String(item.getPayload()));
                super.onNext(item);
            }
        };
        logContainerCmd
                .withStdOut(true)
                .withStdErr(true)
                .exec(logContainerResultCallback)
                .awaitCompletion();
    }


}
